<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
          >新增</el-button
        >
        <el-button
          class="avatar-wrapper"
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleResetPwd"
          v-hasPermi="['system:user:edit']"
          >密码重置</el-button
        >
        <el-dropdown
          @command="handleCommand"
          class="right-menu-item hover-effect"
          trigger="click"
        >
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            v-hasPermi="['system:user:remove']"
            >状态管理</el-button
          >
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="冻结账户">
                <span>冻结账户</span>
              </el-dropdown-item>
              <el-dropdown-item command="注销账户">
                <span>注销账户</span>
              </el-dropdown-item>
              <el-dropdown-item command="初始化">
                <span>初始化</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-form-item>
    </el-form>

    <el-table
      :key="Math.random()"
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
      height="55vh"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" width="50" align="center" />
      <el-table-column
        label="单位"
        align="center"
        prop="organizationFullName"
      />
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="用户姓名" align="center" prop="nickName" />
      <el-table-column label="工号" align="center" prop="jobNumber" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="岗位(职务)" align="center" prop="deptPost" />
      <el-table-column label="性别" align="center" prop="sex">
        <template #default="scope">
          <span>{{ ["男", "女"][scope.row.sex] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="角色"
        align="center"
        prop="rolestr"
      ></el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span>{{ ["正常", "停用", "冻结", "注销"][scope.row.status] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="初始密码"
        align="center"
        prop="dept.initialPassword"
      >
        <template #default="">
          <span>admin123</span>
        </template>
      </el-table-column>
      <el-table-column
        label="最后更新时间"
        align="center"
        prop="updateTime"
        width="120"
      />
      <el-table-column
        label="操作"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="重置密码" placement="top">
            <el-button
              link
              type="primary"
              icon="Key"
              @click="handleResetPwds(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="查看" placement="top">
            <el-button
              link
              type="primary"
              icon="CircleCheck"
              @click="handleAuthRole(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="70%" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="单位" prop="organizationId">
              <el-tree-select
                v-model="form.organizationId"
                :data="deptOptions"
                :props="{
                  value: 'organizationId',
                  label: 'organizationFullName',
                  children: 'children',
                }"
                value-key="organizationId"
                placeholder="选择上级部门"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户名" prop="userName">
              <el-input
                :disabled="isDisabled"
                v-model="form.userName"
                placeholder="请输入用户名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户姓名" prop="nickName">
              <el-input
                :disabled="isDisabled"
                v-model="form.nickName"
                placeholder="请输入用户姓名"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" v-show="title != '修改用户'">
            <el-form-item label="用户密码" prop="passwordIs">
              <el-input
                :disabled="isDisabled"
                v-model="form.passwordIs"
                placeholder="请输入用户密码"
                type="passwordIs"
                maxlength="20"
                show-passwordIs
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工号" prop="jobNumber">
              <el-input
                :disabled="isDisabled"
                v-model="form.jobNumber"
                placeholder="请输入工号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择">
                <el-option
                  placeholder="请选择部门"
                  v-for="item in deptListarr.value"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                  :disabled="isDisabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="岗位(职务)" prop="deptPost">
              <el-input
                :disabled="isDisabled"
                v-model="form.deptPost"
                placeholder="请输入岗位(职务)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-radio-group :disabled="isDisabled" v-model="form.sex">
                <el-radio-button label="0">男</el-radio-button>
                <el-radio-button label="1">女</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="政治面貌" prop="politicsStatus">
              <el-select v-model="form.politicsStatus" placeholder="请选择">
                <el-option
                  v-for="item in ['党员', '群众']"
                  :key="item"
                  :label="item"
                  :value="item"
                  :disabled="isDisabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                :disabled="isDisabled"
                v-model="form.phonenumber"
                placeholder="请输入手机号码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱地址" prop="email">
              <el-input
                :disabled="isDisabled"
                v-model="form.email"
                placeholder="请输入邮箱地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色">
              <el-select
                v-model="form.roleIds"
                multiple
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                :disabled="isDisabled"
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="isDisabled" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { formatDate } from "@/utils";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
  deptListAll,
} from "@/api/system/user";
import { listDept } from "@/api/system/dept";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex"
);

import { encrypt, decrypt } from "@/utils/jsencrypt";

const userList = ref([]);
const deptOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const roleOptions = ref([]);

const isDisabled = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
  },
  rules: {
    userName: [
      {
        required: true,
        message: "用户名称不能为空",
        trigger: ["blur", "change"],
      },
      {
        min: 2,
        max: 20,
        message: "用户名称长度必须介于 2 和 20 之间",
        trigger: ["blur", "change"],
      },
    ],
    nickName: [
      {
        required: true,
        message: "用户昵称不能为空",
        trigger: ["blur", "change"],
      },
    ],
    // password: [
    //   { required: true, message: "用户密码不能为空", trigger: ["blur", "change"] },
    //   { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: ["blur", "change"] },
    // ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phonenumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: ["blur", "change"],
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      loading.value = false;
      userList.value = res.rows;
      total.value = res.total;
      userList.value.forEach((item) => {
        item.rolestr = item.roles
          .map((iitem) => {
            return iitem.roleName;
          })
          .join(",");
      });
    }
  );
}
function getlistDept() {
  listDept().then((response) => {
    deptOptions.value = response.data;
  });
}
getlistDept();
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  handleQuery();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 查看 */
function handleAuthRole(row) {
  const userId = row.userId;
  getUser(userId).then((response) => {
    form.value = response.data;
    roleOptions.value = response.roles;
    form.value.roleIds = response.roleIds;
    open.value = true;
    title.value = "查看";
    form.value.password = "";
    form.value.passwordIs = "";
    isDisabled.value = true;
  });
}

/** 重置密码按钮操作 */
function handleResetPwd() {
  Promise.all(ids.value.map(czmm)).then((res) => {
    proxy.$modal.msgSuccess("已重置密码");
    getList();
  });
}
function czmm(element) {
  return new Promise((resolve) => {
    resetUserPwd(element, encrypt("admin123")).then((res) => {
      resolve(res);
    });
  });
}
function handleResetPwds(row) {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      inputPattern: /^.{8,20}$/,
      inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    })
    .then(({ value }) => {
      resetUserPwd(row.userId, encrypt(value)).then((response) => {
        proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
      });
    })
    .catch(() => {});
}
// 状态管理
function handleCommand(command) {
  let type = undefined;
  switch (command) {
    case "冻结账户":
      type = 2;
      break;
    case "注销账户":
      type = 3;
      break;
    case "初始化":
      type = 0;
      break;
    default:
      break;
  }
  Promise.all(ids.value.map((item) => ztgg(item, type))).then((res) => {
    proxy.$modal.msgSuccess("状态已更改");
    getList();
  });
}
function ztgg(element, type) {
  return new Promise((resolve) => {
    changeUserStatus(element, type).then((res) => {
      resolve(res);
    });
  });
}
/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = !selection.length;
  multiple.value = !selection.length;
}
/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    organizationFullName: undefined,
    organizationId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    passwordIs: undefined,
    jobNumber: undefined,
    deptId: undefined,
    deptName: undefined,
    deptPost: undefined,
    sex: undefined,
    politicsStatus: undefined,
    phonenumber: undefined,
    email: undefined,
    roleId: undefined,
    remark: undefined,
    loginDate: undefined,
  };
  proxy.resetForm("userRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  getUser().then((response) => {
    roleOptions.value = response.roles;

    title.value = "添加用户";
    form.value.password = "";
    form.value.passwordIs = "";
    isDisabled.value = false;
    rules.value = {
      userName: [
        {
          required: true,
          message: "用户名称不能为空",
          trigger: ["blur", "change"],
        },
        {
          min: 2,
          max: 20,
          message: "用户名称长度必须介于 2 和 20 之间",
          trigger: ["blur", "change"],
        },
      ],
      nickName: [
        {
          required: true,
          message: "用户昵称不能为空",
          trigger: ["blur", "change"],
        },
      ],
      passwordIs: [
        {
          required: true,
          message: "用户密码不能为空",
          trigger: ["blur", "change"],
        },
        {
          min: 8,
          max: 20,
          message: "用户密码长度必须介于 5 和 20 之间",
          trigger: ["blur", "change"],
        },
      ],
      email: [
        {
          type: "email",
          message: "请输入正确的邮箱地址",
          trigger: ["blur", "change"],
        },
      ],
      phonenumber: [
        {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: ["blur", "change"],
        },
      ],
      deptId: [
        {
          required: true,
          message: "部门不能为空",
          trigger: ["blur", "change"],
        },
      ],
    };
    open.value = true;
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const userId = row.userId;
  getUser(userId).then((response) => {
    form.value = response.data;
    roleOptions.value = response.roles;
    form.value.roleIds = response.roleIds;
    title.value = "修改用户";
    form.value.password = "";
    form.value.passwordIs = "";
    isDisabled.value = false;
    rules.value = {
      userName: [
        {
          required: true,
          message: "用户名称不能为空",
          trigger: ["blur", "change"],
        },
        {
          min: 2,
          max: 20,
          message: "用户名称长度必须介于 2 和 20 之间",
          trigger: ["blur", "change"],
        },
      ],
      nickName: [
        {
          required: true,
          message: "用户昵称不能为空",
          trigger: ["blur", "change"],
        },
      ],
      email: [
        {
          type: "email",
          message: "请输入正确的邮箱地址",
          trigger: ["blur", "change"],
        },
      ],
      phonenumber: [
        {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: ["blur", "change"],
        },
      ],
    };
    open.value = true;
  });
}
const deptListarr = reactive([]);
//获取部门用户
function funlistDept() {
  deptListAll().then((res) => {
    deptListarr.value = res.data;
    console.log(deptListarr.value);
  });
}
funlistDept();
/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      deptListarr.value.forEach((item) => {
        if (item.deptId == form.value.deptId) {
          form.value.deptName = item.deptName;
        }
      });
      if (form.value.userId != undefined) {
        updateUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.password = encrypt(form.value.passwordIs);
        addUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

getList();
</script>
